﻿using Microsoft.Extensions.DependencyInjection;

namespace Microsoft.AspNetCore.App
{
    public static class MiddlwareExtensions
    {
        public static void UseMiddlware<T>(this IApplicationBuilder builder, params object[] args)
            where T : IMiddleware
        {
            builder.Use(next => 
            {
                return async context => 
                {
                    var list = new List<object>(args)
                    {
                        next
                    };
                    var middleware = ActivatorUtilities.CreateInstance<T>(context.Services, list.ToArray());
                    await middleware.Invoke(context);
                };
            });
        }
    }
}
